package com.wq.jdk8;

import java.util.Random;

/**
 * @Author: wangqiang20995
 * @Date:2018/8/16
 * @Description:
 * @Resource:
 */
public class Java8InterfaceDemo {

    public static void main(String args[]) {
        //使用接口上的默认实现
        MathAction actionInterface = new AddMathAction();
        System.out.println("default method in interface --> " + actionInterface.action(1, 2.2));
        System.out.println();

        //lambda 表达式
        MathAction actionLambda = (a, b) -> {
            System.out.println("计算lambda表达式的值");
            return a * b;
        };
        System.out.println("lambda expression --> " + actionLambda.action(1, 2));
        System.out.println();

        //函数式
        ProductFactory productFactory = (type) -> {
            System.out.println("produce [" + type + "]");
            return new Random().nextInt(10);
        };
        System.out.println("function programming --> " + productFactory.produce("Fruit"));
        System.out.println();

        //方法与构造函数的引用--> ::
        ConvertToString convertToString = new Object()::toString;
        System.out.println("method and constructor --> " + convertToString.convert());
        System.out.println();

        //访问局部变量
        int index = 1;//不声明为final，但是实际上却是final
        MathAction param = (a, b) -> a + b + index;
        System.out.println("visit part param --> "+ param.action(3,3));
        System.out.println();

    }
}


class AddMathAction implements MathAction {

    @Override
    public double action(double a, double b) {
        return defaultAction(a, b);
    }
}

interface MathAction {

    double action(double a, double b);

    //接口实现默认方法
    default double defaultAction(double a, double b) {
        return a + b;
    }
}

@FunctionalInterface
interface ProductFactory {
    //    “函数式接口”是指仅仅只包含一个抽象方法的接口，每一个该类型的lambda表达式都会被匹配到这个抽象方法。因为 默认方法 不算抽象方法，所以你也可以给你的函数式接口添加默认方法。
    int produce(String type);

//    如果被@FunctionalInterface标注了的类有多个抽象方法，那么就会报错
//    void display();
}


interface ConvertToString {
    String convert();
}